$(function() {
    var bdbplatDomain = {
        /* 初始数据 */
        defData: {
            pageSize: 20
        },

        /* 页面状态 */
        pageState: {
            search: '', // 搜索框值.
            page: 1, // 分页值.
            noData: 'def' // search: 没有匹配的结果; def: 暂无记录.
        },
        resetPageState: function() {
            this.pageState = {
                search: '',
                page: 1,
                noData: 'def'
            };

            this.list();
        },

        /* 添加 */
        addEvent: function() {
            var _this = this,
                formVerify;

            formVerify = $('#bdb-platDomain-add-form').validate({
                errorElement: "div",
                errorPlacement: function(error, element) {
                    error.addClass("help-block");
                    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
                        element.parents(".bdb-vc").find('.help-block').remove();
                        error.appendTo(element.parents(".bdb-vc"));
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(form, e) {
                    e.preventDefault();
                    _this.addSubmit(form);
                }
            });

            $('#bdb-platDomain-add').off('click').on('click', function(e) {
                bdbMain.mLRManag({mask: true});
                _this.addDefDataProc(formVerify);
            });
        },
        addDefDataProc: function(formVerify) {
            var _this = this;
            bdbMain.mLRManag({mask: true, loading: true});
            $.post('/PlatDomain/getInitData', function(response) {
                if (response.code == 0) {
                    _this.addDefDataProcTpl(response.data, formVerify);
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        addDefDataProcTpl: function(data, formVerify) {
            var _this = this,
                serverGroupHtml = '',
                ele = $('#bdb-platDomain-add-form');

            // 服务器组列表.
            $.each(data.serverGroupList, function(i, n) {
                serverGroupHtml += '<li class="list-row">\
                                        <input class="bdb-f-l list-row-input" type="checkbox" name="server_group_ids[]" value="' + n.id + '" \
                                            data-rule-required="true" data-msg-required="请选择服务器组">\
                                        <span>' + n.name + '</span>\
                                    </li>';
            });
            serverGroupHtml += '<li class="bdb-hide bdb-search-multisel-null">没有匹配的内容!</li>';
            ele.find('.list').html(serverGroupHtml);

            // 域.
            ele.find('#domain-add').val(data.domain);

            $('.bdb-search-multisel').bdbSearchMultisel({eleName: 'server_group_ids[]'});
            bdbMain.mLSleep({loading: false}, function() {
                $(".bdbBlankEle").bdbDialog({
                    ele: '#bdb-platDomain-add-dialog',
                    formObj: formVerify,
                    form: $('#bdb-platDomain-add-form'),
                    verifyResetInfo: true,
                    procFun: function() {
                        $('#bdb-platDomain-add-form .items').hide().empty();
                    }
                });

                ele.find('.list').scrollTop(0);
            });
        },
        addSubmit: function(form) {
            var _this = this,
                form = $(form);

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 服务器组id列表.
            var serverGroupIds = '',
                serverGroupIdArr = [],
                serverGroupEles = form.find('.list-row-input:checked');

            $.each(serverGroupEles, function(i, n) {
                serverGroupIdArr.push($(n).val());
            });
            serverGroupIds = serverGroupIdArr.join(',');

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
            $.post('/PlatDomain/addPlatDomain', {
                subzone: form.find('#subzone-add').val(),
                server_group_ids: serverGroupIds
            }, function(response) {
                if (response.code == 0) {
                    $(".js-bdb-dialog-cancel").click();
                    bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 1, msg: '添加成功.'}});
                    bdbMain.mLSleep({}, function() {
                        _this.resetPageState();
                    });
                } else {
                    bdbMain.mLSleep({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },

        /* 搜索 */
        searchEvent: function() {
            var _this = this,
                searchInputEle = $('.bdb-search-input');

            searchInputEle.off('focusin').on('focusin', '.search-text', function(e) {
                var _cThis = $(this),
                    _btnEle = $(this).parent().find('span');

                if (!_btnEle.hasClass('search-clear')) {
                    _cThis.animate({width: '240px'}, 500);
                    _btnEle.animate({left: '240px'}, 500, function() {
                        _btnEle.removeClass('search-gray').addClass('search-blue');
                    });
                }
            });

            searchInputEle.off('click').on('click', 'span', function(e) {
                var left = parseInt($(this).css('left'));
                if ($(this).hasClass('search-blue') && left > 0) {
                    _this.pageState.search = searchInputEle.find('.search-text').val();
                    _this.pageState.noData = 'search';
                    $(this).removeClass('search-blue').addClass('search-clear');
                    _this.list();
                } else if (left > 0) {
                    _this.pageState.search = '';
                    _this.pageState.noData = 'def';
                    searchInputEle.find('.search-text').val('');
                    $(this).removeClass('search-clear').addClass('search-blue');
                    _this.list();
                }
            });
        },

        /* 列表 */
        list: function(obj) {
            var _this = this,
                obj = obj || {page: 1};

            _this.pageState.page = obj.page;
            bdbMain.mLRManag({mask: true, loading: true});

            // 获取列表.
            $.post('/PlatDomain/platDomainList', {
                pageSize: _this.defData.pageSize,
                pageNumber: _this.pageState.page,
                query: _this.pageState.search
            }, function(response) {
                if (response.code == 0 ) {
                    var listHtml = _this.listProc(response.data.list),
                        totalRowCnt = parseInt(response.data.totalCount) > 0 ? parseInt(response.data.totalCount) : 0;

                    _this.listNull(totalRowCnt);
                    $('.bdb-list').html(listHtml);
                    bdbMain.mLSleep({mask: false, loading: false});

                    // 分页插件.
                    $("#js-bdb-creatPage").bdbPagination({
                        totalRowCnt: totalRowCnt,
                        currentPage: _this.pageState.page,
                        pageSize: _this.defData.pageSize
                    });
                    $('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}', totalRowCnt));

                    // tip.
                    $('.js-platdomain-servergroup-tip').bdbTip({
                        eleTopMargin: 129,
                        eleBottomMargin: 53,
                        space: 0,
                        left: 0,
                        minWidth: 280,
                        maxWidth: 280,
                        padding: '6px 24px 6px 26px',
                        tpl: '<div class="col-md-12 bdb-ellipsis bdb-text-align-l">{data}</div>'
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        listProc: function(list) {
            var _this = this,
                tplHtml = '',
                serverGroupArr = [];
                serverGroupText = '';

            $.each(list, function(i, n) {
                serverGroupArr = [];
                $.each(n.server_group_list, function(i, n) {
                    serverGroupArr.push(n);
                });

                tplHtml += "<div class='bdb-list-row' data-id='" + n.plat_domain_id + "'>\
                                <div class='bdb-mx-w-col-1 bdb-ellipsis'>" + n.subzone + "</div>\
                                <div class='bdb-mx-w-col-2 bdb-ellipsis'>" + n.domain + "</div>\
                                <div class='bdb-mx-w-col-3 bdb-p-r'>\
                                    <div class='js-platdomain-servergroup-tip bdb-ellipsis' data-title='" + JSON.stringify(n.server_group_list) + "'>" + serverGroupArr.join(" / ") + "</div>\
                                </div>\
                                <div class='bdb-mx-w-col-4 bdb-ellipsis bdb-text-align-c'>" + n.username + "</div>\
                                <div class='bdb-mx-w-col-5 bdb-ellipsis'>" + n.update_time + "</div>\
                                <div class='bdb-mx-w-col-6'>\
                                    <div class='bdb-option-btn bdb-p-r bdb-mgn-t-10'>\
                                        <a href='/PlatDomainLine/lineList/" + n.plat_domain_id + "'>设置策略</a>\
                                    </div>\
                                </div>\
                            </div>";
            });

            return tplHtml;
        },
        listNull: function(totalRowCnt) {
            var noResult = $('.bdb-no-result'),
                noSearchRecord = $('.bdb-no-search-record');

            if (totalRowCnt <= 0) {
                if (this.pageState.noData == 'search') { // 查询.
                    noResult.hide();
                    noSearchRecord.show();
                } else { // 暂无记录.
                    noResult.show();
                    noSearchRecord.hide();
                }
            } else {
                noResult.hide();
                noSearchRecord.hide();
            }
        },

        /* 分页 */
        pageEvent: function() {
            var　_this = this;

            /* 页码事件 */
            $('.bdb-creatPage').off('click').on('click', '.bdb-pagination', function(e) {
                e.preventDefault();
                var ele = $(e.target),
                page = parseInt(ele.text());

                if (!isNaN(page)) {
                    _this.list({page: page});
                }
            });
        },

        /* 屏幕高度适应 */
        contentSizeResize: function() {
            $(window).resize(function() {
                $('.bdb-list').bdbScreenH(1);
            });
        },

        init: function() {
            var _this = this;

            _this.list();
            _this.addEvent();
            _this.pageEvent();
            _this.searchEvent();
            _this.contentSizeResize();

            $('.bdb-list').bdbScreenH(1);
        }
    };

    bdbplatDomain.init();
});
